package com.bdmc.smokesensor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.Utils.WebTokenUtil;
import com.bdmc.smokesensor.annotation.AuthIgnore;
import com.bdmc.smokesensor.models.LoginInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MySpringMVCConfig implements WebMvcConfigurer {

    public static final Logger logger = LoggerFactory.getLogger((MySpringMVCConfig.class));

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // if(!registry.hasMappingForPattern("/static/**"))
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/export/**").addResourceLocations("files/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS").maxAge(3600);

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new SessionHandlerInterceptor());
        interceptorRegistration.addPathPatterns("/**").excludePathPatterns("/files/**", "/excel/**", "/image/**","/user/login",
                "/testuser/*", "/msg/*","/ct/*");
    }

    private class SessionHandlerInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            if (request.getMethod().equals("OPTIONS"))
                return true;
            AuthIgnore annotation;
            if (handler instanceof HandlerMethod) {
                annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
            } else {
                annotation=null;
            }
            // 如果有@IgnoreAuth注解，则不验证token
            if (annotation != null) {
                return true;
            }
            boolean handleResult = false;
            String token = request.getHeader("token");
            LoginInfo logininfo = WebTokenUtil.validateJWT(token);
            if (logininfo == null) {// fanhui 401
                PrintWriter writer = null;
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html; charset=utf-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

                try {
                    writer = response.getWriter();
                    String error = "token信息有误";
                    Msg m = ResultUtil.error(-1, error);
                    writer.print(JSON.toJSONString(m));
                    return handleResult;
                } catch (IOException e) {
                    logger.error("response error", e);
                } finally {
                    if (writer != null)
                        writer.close();
                }
            }

            request.setAttribute("user_id", logininfo.id);
            request.setAttribute("dep_id", logininfo.dep_id);
            request.setAttribute("loginName", logininfo.loginName);
            handleResult = true;
            return handleResult;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) {
            // controller方法处理完毕后，调用此方法
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) {
            // 页面渲染完毕后调用此方法_
            // request.getAttribute(LOGGER_)
        }

    }

}